import React, { useRef, useState } from 'react';
import { PlusOutlined, EllipsisOutlined } from '@ant-design/icons';
import {
  Button,
  Modal,
  Form,
  Input,
  DatePicker,
  Divider,
  message,
  Select,
  Popconfirm,
  InputNumber,
} from 'antd';
import type { ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import locale from 'antd/es/date-picker/locale/zh_CN';
import { motifColumns } from './data';
import type { MotifItem, customerListItem } from './data.d';
import TableTitle from '@/components/TableTitle';
import {
  getMotionList,
  createMotion,
  getAccountCategoryByCustomerNo,
  publishMotion,
  getCustomerList,
  getMotionInfo,
  editMotion,
  deleteMotion,
} from './service';
import moment from 'moment';
import { getLocalStorageInfo } from '@/utils/localStorageInfo';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { TextArea } = Input;

const MotionManagement = () => {
  // 控制新增、修改提案模态框显示
  const [isMotionModalVisible, setIsMotionModalVisible] = useState(false);
  // 控制新增、修改提案模态框标题
  const [motionModalTitle, setMotionModalTitle] = useState(true);
  // 新增、修改提案类型
  const [motionType, setMotionType] = useState<string>();
  // 候选人列表
  const [customerList, setCustomerList] = useState<customerListItem[]>([]);
  // 币种信息
  const [isccy, setIsccy] = useState<any[]>([]);
  // 控制提案详情模态框显示
  const [isViewModalVisible, setIsViewModalVisible] = useState(false);
  // 查看的数据
  const [viewInfo, setViewInfo] = useState<MotifItem>();

  /**
   * 点击查看调用
   */
  const handleView = (record: MotifItem) => {
    setViewInfo(record);
    setIsViewModalVisible(true);
  };

  const handleEditModel = (record: MotifItem) => {
    setIsMotionModalVisible(true);
    setMotionModalTitle(false);
    setViewInfo(record);
    let time = [
      moment(record.startTime, 'YYYY-MM-DD'),
      moment(record.endTime, 'YYYY-MM-DD'),
    ];
    motionForm.setFieldsValue({ ...record, time });
  };

  const confirmDel = async (serialNo: string) => {
    let res = await deleteMotion({ serialNo });
    console.log(res);
    if (res.code !== '000000') return message.success('删除失败！');
    message.success('删除成功！');
    actionRef.current?.reload();
  };

  // 定义操作单元格
  const columnsOptionRender = (text: any, record: MotifItem) => {
    return [
      <div key={record.serialNo}>
        <a onClick={() => handleView(record)}>查看</a>
        <Divider type="vertical" />
        {record.status == 1 ? (
          <>
            <a
              onClick={() => {
                handleEditModel(record);
                setMotionType(record.type);
              }}
            >
              修改
            </a>
            <Divider type="vertical" />
            <Popconfirm
              title="是否发布此提案?"
              onConfirm={async () => {
                let res = await publishMotion({ serialNo: record.serialNo });
                console.log(res);
                if (res.code !== '000000') return message.success('发布失败！');
                message.success('发布成功！');
                actionRef.current?.reload();
              }}
              onCancel={() => {
                message.warning(`取消发布`);
              }}
              okText="是"
              cancelText="否"
            >
              <a>发布</a>
            </Popconfirm>
            <Divider type="vertical" />
            <Popconfirm
              title="是否删除此条数据?"
              onConfirm={() => confirmDel(record.serialNo)}
              onCancel={() => {
                message.warning(`取消删除`);
              }}
              okText="是"
              cancelText="否"
            >
              <a>删除</a>
            </Popconfirm>
          </>
        ) : null}
      </div>,
    ];
  };

  // 列渲染样式赋值
  motifColumns.forEach((item) => {
    item.dataIndex === 'action'
      ? (item.render = columnsOptionRender)
      : undefined;
  });

  /**
   * 获取客户列表
   */
  const getCustomers = async (nickname?: string) => {
    let res = nickname
      ? await getCustomerList({
          nickname,
          pageSize: 50,
          current: 1,
        })
      : await getCustomerList({
          pageSize: 50,
          current: 1,
        });
    console.log(res);
    if (res.code !== '000000')
      return message.info('获取候选人列表失败，请稍后再试！');
    setCustomerList(res.data);
  };

  /**
   * 获取币种
   */
  const getCcy = () => {
    let customerInfo = getLocalStorageInfo('customerInfo');
    getAccountCategoryByCustomerNo({
      customerNo: customerInfo.customerNo,
    }).then((res) => {
      let resultArr = res.data.map((item: any) => {
        console.log('item', item);
        return item.ccy;
      });
      // 数组去重,获得币种
      let newResultArr = [...new Set(resultArr)];
      console.log('newResultArr🎉', newResultArr);
      setIsccy(newResultArr);
    });
  };

  /**
   * 打开新增、修改提案模态框调用
   */
  const showMotionModal = () => {
    getCustomers();
    getCcy();
    setMotionModalTitle(true);
    setIsMotionModalVisible(true);
  };

  /**
   * 搜索客户调用
   * @param nickname 搜索内容
   */
  const searchCustomerNo = (nickname: string) => {
    console.log(nickname);
    getCustomers(nickname);
  };

  /**
   * 点击新增、修改提案模态框确定调用
   */
  const handleMotionOk = async () => {
    await motionForm.validateFields();
    let response = motionForm.getFieldsValue();
    let customerInfo = getLocalStorageInfo('customerInfo');
    response.proposalBy = customerInfo.customerNo;
    console.log(response);
    const { time } = response;
    response.startTime = time[0].format('YYYY-MM-DD');
    response.endTime = time[1].format('YYYY-MM-DD');
    console.log(response.startTime, response.endTime);
    delete response.time;
    console.log(response);
    let res = await createMotion(response);
    console.log(res);
    if (res.code !== '000000') return message.info('添加失败');
    message.success('添加成功');
    actionRef.current?.reload();
    motionForm.resetFields();
    setIsMotionModalVisible(false);
  };

  /**
   * 关闭新增、修改提案模态框调用
   */
  const handleMotionCancel = () => {
    setIsMotionModalVisible(false);
    motionForm.resetFields();
  };
  // 绑定表格
  const actionRef = useRef<ActionType>();
  // 绑定表单
  const [motionForm] = Form.useForm();
  return (
    <>
      <ProTable<MotifItem>
        headerTitle={<TableTitle title="提案管理" />}
        scroll={{ x: 900 }}
        columns={motifColumns}
        actionRef={actionRef}
        cardBordered
        bordered
        rowKey="serialNo"
        dateFormatter="string"
        search={{
          labelWidth: 'auto',
        }}
        columnsState={{
          persistenceKey: 'motif-table',
          persistenceType: 'localStorage',
        }}
        // 分页相关配置
        pagination={{
          // 初始页面数据条数
          pageSize: 10,
        }}
        toolBarRender={() => [
          <Button
            key="button"
            onClick={() => {
              setMotionModalTitle(true);
              showMotionModal();
            }}
            icon={<PlusOutlined />}
            type="primary"
          >
            新增提案
          </Button>,
        ]}
        // 请求获取的数据
        request={async (params) => {
          console.log(params);

          let res = await getMotionList({ ...params });
          console.log(res);
          console.log('🎉');
          const result = {
            data: res.data,
            total: res.pagination.totalSize,
          };
          return result;
        }}
      />
      {/* 新增、修改提案模态框 */}
      <Modal
        width={600}
        title={motionModalTitle ? '添加提案' : '修改提案'}
        visible={isMotionModalVisible}
        onOk={handleMotionOk}
        onCancel={handleMotionCancel}
      >
        <Form
          name="basic"
          form={motionForm}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 16 }}
          initialValues={{ remember: true }}
          autoComplete="off"
        >
          <Form.Item
            label="提案名称"
            name="name"
            rules={[{ required: true, message: '请填写提案名称!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="提案code"
            name="voteCode"
            rules={[{ required: true, message: '请填写提案code!' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="提案类型"
            name="type"
            rules={[{ required: true, message: '请选择提案类型!' }]}
          >
            <Select
              disabled={isViewModalVisible}
              onChange={(e) => setMotionType(e)}
              style={{ width: '100%' }}
            >
              <Option value={1}>薪酬</Option>
              <Option value={2}>普通</Option>
            </Select>
          </Form.Item>
          {motionType == '1' ? (
            <>
              <Form.Item
                label="会员选择"
                name="customerNo"
                rules={[{ required: true, message: '请选择会员!' }]}
              >
                <Select
                  showSearch
                  filterOption={false}
                  onSearch={searchCustomerNo}
                  style={{ width: '100%' }}
                >
                  {customerList.map((item) => {
                    return item.nickname ? (
                      <Option key={item.customerNo} value={item.customerNo}>
                        {item.nickname}
                      </Option>
                    ) : null;
                  })}
                </Select>
              </Form.Item>
              <Form.Item
                label="薪酬金额"
                name="amount"
                rules={[{ required: true, message: '请填写薪酬金额!' }]}
              >
                <InputNumber style={{ width: '100%' }} min={0} />
              </Form.Item>
              <Form.Item
                label="币种"
                name="ccy"
                rules={[{ required: true, message: '请填写币种!' }]}
              >
                <Select>
                  {isccy.map((currentValue, index) => {
                    return (
                      <Option value={currentValue} key={index}>
                        {currentValue}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </>
          ) : null}
          <Form.Item
            label="最小通过数"
            name="minPass"
            rules={[{ required: true, message: '请填写最小通过数!' }]}
          >
            <InputNumber style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            label="投票通过率(%)"
            name="passRate"
            rules={[{ required: true, message: '请填写投票通过率!' }]}
          >
            <InputNumber style={{ width: '100%' }} min={0} step="0.01" />
          </Form.Item>
          <Form.Item
            label="提案时间"
            name="time"
            rules={[{ required: true, message: '请选择提案时间!' }]}
          >
            <RangePicker
              showTime={{ format: 'YYYY-MM-DD' }}
              format="YYYY-MM-DD"
              locale={locale}
            />
          </Form.Item>
          <Form.Item
            label="提案描述"
            name="description"
            rules={[{ required: true, message: '请填写提案描述!' }]}
          >
            <TextArea />
          </Form.Item>
        </Form>
      </Modal>
      {/* 查看模态框 */}
      <Modal
        bodyStyle={{ margin: 0, padding: 0 }}
        width={1000}
        title="提案详情"
        visible={isViewModalVisible}
        onCancel={() => {
          setIsViewModalVisible(false);
        }}
        footer={[]}
      ></Modal>
    </>
  );
};

export default MotionManagement;
